package com.xframe.xdal.core.model.sqlbuilder.proc;

import com.xframe.xdal.core.constant.ErrorCode;
import com.xframe.xdal.core.exception.DalFrameException;
import com.xframe.xdal.core.model.mapping.ITableInfo;
import com.xframe.xdal.core.model.sqlbuilder.BaseSqlBuilder;
import com.xframe.xdal.core.model.sqlbuilder.BuilderContext;
import com.xframe.xdal.core.model.sqlbuilder.SqlExpression;
import com.xframe.xdal.core.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 自由的 构造删除sql语句
 * @ClassName: TestManyDelete
 * @Author: Lean.Liu
 * @CreateTime: 2023/4/6 10:34
 **/
public class DefDeleteManySqlBuilder extends BaseSqlBuilder {
    /**
     * 删除 sql 语句
     *
     * @return 返回sql语句
     */
    public String getSQL() {
        return " delete from %s where 1 = 1%s ";
    }
    @Override
    public SqlExpression build(BuilderContext context) {
        if (context.getConditionValueCollection().getConditionValues() != null
                && context.getConditionValueCollection().getConditionValues().size() > 0) {
            List<Object> pList = new ArrayList<>();
            StringBuilder whereBuilder = new StringBuilder();
            ITableInfo tableInfo = context.getTableInfo();
            context.getConditionValueCollection().builderWhereByKeyNoQuery(context,tableInfo,context.getColPlaceholder(),whereBuilder,pList);
            if (StringUtil.isEmpty(whereBuilder)){
                throw new DalFrameException(ErrorCode.TABLEINFO_NO_FIND,"删除条件字段与数据库字段不匹配");
            }
            String deleteSql = String.format(getSQL(), context.getColPlaceholder()
                    + context.getNameConvert().toName(tableInfo.getName()) + context.getColPlaceholder(), whereBuilder);
        return new SqlExpression(deleteSql, pList,context.getDataSourceTypeEnums());

        } else {
            throw new DalFrameException(ErrorCode.ARGS_ERROR,"删除条件不能为空");
        }
    }
}
